<template>
  <div class="group-list">
    <div class="group-list-header">
      <h3>资料库列表</h3>
      <div class="header-buttons">
        <button 
          class="add-group-btn" 
          @click="$emit('create-group')"
          :disabled="isLoading"
          title="新建资料库"
          v-if="isAdmin"
        >
          <span>+</span>
        </button>
      </div>
    </div>
    <div class="group-list-content">
      <div 
        v-for="group in sortedGroups" 
        :key="group.id" 
        class="group-item"
        :class="{ 'active': selectedGroup && selectedGroup.id === group.id }"
        @click="$emit('select-group', group)"
      >
        <div class="group-name">{{ group.name }}</div>
        <div class="group-actions" v-if="selectedGroup && selectedGroup.id === group.id">
          <button 
            class="action-menu-btn" 
            @click.stop="toggleMenu(group.id)"
            title="操作"
            v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole"
          >
            <span>⋮</span>
          </button>
          <div 
            v-if="activeMenu === group.id" 
            class="action-menu"
            @click.stop
          >
            <div 
               v-if="group.open === 0 && (isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole)" 
              class="menu-item" 
              @click="showEditModal(group)"
            >
              <span>修改资料库</span>
            </div>
            <div 
               v-if="group.open === 0 && (isAdmin || isAdvancedLibraryAdmin || isAssignRole)" 
              class="menu-item" 
              @click="showUserManageModal(group)"
            >
              <span>用户权限管理</span>
            </div>
            <div 
               v-if="(isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole)" 
              class="menu-item delete" 
              @click="confirmDelete(group)"
            >
              <span>删除资料库</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="groups.length === 0 && !isLoading" class="empty-state">
        暂无资料库
      </div>
      <div v-if="isLoading" class="loading-state">
        加载中...
      </div>
    </div>
  </div>
  
  <!-- 用户管理模态框 -->
  <GroupUserManageModal
    v-if="showUserModal && selectedGroupForUsers"
    :show="showUserModal"
    :groupId="selectedGroupForUsers.id"
    @close="showUserModal = false"
  />
  
  <!-- 编辑模态框 -->
  <div v-if="editModalVisible && selectedGroupForEdit" class="modal-overlay">
    <div class="modal-container">
      <div class="modal-header">
        <h3>修改资料库</h3>
        <button class="close-btn" @click="editModalVisible = false">&times;</button>
      </div>
      
      <div class="modal-body">
        <div class="form-group">
          <label>资料库名称</label>
          <input 
            type="text" 
            v-model="selectedGroupForEdit.name" 
            placeholder="请输入资料库名称"
          />
        </div>
        
        <div class="form-group">
          <label>是否公开</label>
          <select v-model="selectedGroupForEdit.open">
            <!-- <option :value="1">公开</option> -->
            <option :value="0">保密</option>
          </select>
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="cancel-btn" @click="editModalVisible = false">取消</button>
        <button 
          class="submit-btn" 
          @click="handleEditSubmit"
          :disabled="!selectedGroupForEdit.name || selectedGroupForEdit.open === null"
        >
          确定
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref,computed } from 'vue';
import { ElMessage } from 'element-plus';
import { API_CONFIG } from '../../config/apiConfig';
import type { KnowledgeBaseGroup } from '../../stores/knowledgebaseStore';
import GroupUserManageModal from './GroupUserManageModal.vue';
import { User } from '../../types'

const props = defineProps<{
  groups: KnowledgeBaseGroup[];
  selectedGroup: KnowledgeBaseGroup | null;
  isLoading: boolean;
}>();

// 获取当前登录用户信息
const userInfoStr = localStorage.getItem('userInfo');
const currentUser = ref<User | null>(userInfoStr ? JSON.parse(userInfoStr) : null);
const isAdmin = computed(() => currentUser.value?.roleName === '超级管理员');
const isAdvancedLibraryAdmin = computed(() => {
  if (isAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === props.selectedGroup?.id && roleId === 6
  );
});
const isEditRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === props.selectedGroup?.id && roleId === 7
  );
});
const isAssignRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === props.selectedGroup?.id && roleId === 11
  );
});

// 排序后的资料库列表
const sortedGroups = computed(() => {
  return [...props.groups]
    .sort((a, b) => (b.open || 0) - (a.open || 0))
    .map(group => ({
      ...group,
      name: group.open === 0 ? `【保密】${group.name}` : `【公开】${group.name}`
    }));
});

const emit = defineEmits<{
  (e: 'select-group', group: KnowledgeBaseGroup): void;
  (e: 'delete-group', groupId: string): void;
  (e: 'create-group'): void;
}>();

// 下拉菜单状态
const activeMenu = ref<string | null>(null);

// 用户管理模态框状态
const showUserModal = ref(false);
const selectedGroupForUsers = ref<KnowledgeBaseGroup | null>(null);

// 编辑模态框状态
const editModalVisible = ref(false);
const selectedGroupForEdit = ref<KnowledgeBaseGroup | null>(null);

// 切换下拉菜单
const toggleMenu = (groupId: string) => {
  if (activeMenu.value === groupId) {
    activeMenu.value = null;
  } else {
    activeMenu.value = groupId;
  }
  
  // 点击外部关闭菜单
  if (activeMenu.value) {
    const closeMenu = () => {
      activeMenu.value = null;
      document.removeEventListener('click', closeMenu);
    };
    setTimeout(() => {
      document.addEventListener('click', closeMenu);
    }, 0);
  }
};

// 显示用户管理模态框
const showUserManageModal = (group: KnowledgeBaseGroup) => {
  selectedGroupForUsers.value = group;
  showUserModal.value = true;
  activeMenu.value = null; // 关闭下拉菜单
};

// 显示编辑模态框
const showEditModal = (group: KnowledgeBaseGroup) => {
  selectedGroupForEdit.value = group;
  editModalVisible.value = true;
  activeMenu.value = null; // 关闭下拉菜单
};

// 确认删除资料库
const confirmDelete = (group: KnowledgeBaseGroup) => {
  if (confirm(`确定要删除资料库 "${group.name}" 吗？`)) {
    emit('delete-group', group.id);
    activeMenu.value = null; // 关闭下拉菜单
  }
};

// 处理编辑提交
const handleEditSubmit = async () => {
  if (!selectedGroupForEdit.value) return;
  
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base-group/${selectedGroupForEdit.value.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        name: selectedGroupForEdit.value.name,
        open: selectedGroupForEdit.value.open
      })
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    if (result.code === '0') {
      ElMessage.success('资料库修改成功');
      editModalVisible.value = false;
      emit('select-group', selectedGroupForEdit.value); // 更新选中状态
    } else {
      ElMessage.error(result.msg || '修改失败');
    }
  } catch (error) {
    console.error('修改资料库失败:', error);
    ElMessage.error('修改失败，请检查网络连接');
  }
};
</script>

<style scoped>
.group-list {
  flex: 0 0 200px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  margin-right: 20px;
}

.group-list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.group-list-header h3 {
  margin: 0;
  color: #333;
}

.add-group-btn {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  padding: 0;
  transition: all 0.2s;
}

.add-group-btn:hover:not(:disabled) {
  background-color: #45a049;
}

.add-group-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.add-group-btn span {
  font-size: 18px;
  font-weight: bold;
}

.group-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.group-item:hover {
  background-color: #f5f5f5;
}

.group-item.active {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.group-name {
  font-weight: 500;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.group-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
  position: relative;
}

.group-item:hover .group-actions {
  opacity: 1;
}

.action-menu-btn {
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
  color: #666;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  padding: 0;
  transition: all 0.2s;
}

.action-menu-btn:hover {
  background-color: #f5f5f5;
}

.action-menu-btn span {
  font-size: 14px;
  font-weight: bold;
}

.action-menu {
  position: absolute;
  right: 0;
  top: 24px;
  width: 120px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10;
  overflow: hidden;
}

.menu-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #f0f0f0;
}

.menu-item.delete {
  color: #ff4d4f;
}

.menu-item.delete:hover {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.empty-state, .loading-state {
  padding: 20px;
  text-align: center;
  color: #999;
}

/* 编辑模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
}

.form-group input, .form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
  border-top: 1px solid #e0e0e0;
  gap: 10px;
}

.cancel-btn {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:hover:not(:disabled) {
  background-color: #40a9ff;
}

.submit-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}
</style>